package com.groupseven.happycampus.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.groupseven.happycampus.common.bo.MenuBo;
import com.groupseven.happycampus.common.listener.R;
import com.groupseven.happycampus.common.listener.WebCanteenListener;
import com.groupseven.happycampus.common.pojo.LayuiPage;
import com.groupseven.happycampus.common.pojo.Menu;
import com.groupseven.happycampus.common.pojo.Restaurant_food;
import com.groupseven.happycampus.common.pojo.User;
import com.groupseven.happycampus.service.CanteenService;
import com.groupseven.happycampus.common.utils.OSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/canteen")
public class CanteenController {

    @Autowired
    private CanteenService canteenService;

    @Autowired
    private WebCanteenListener webCanteenListener;


    @RequestMapping("/list")
    @ResponseBody //将数据转换为json格式发送给前端
    //RequestParam 必须加此 注解 否则无法接受到
    public LayuiPage<Menu> limitMenu(@RequestParam Map<String, String> parms) {
        return canteenService.menuList(parms);
    }
    @RequestMapping("/list2")
    @ResponseBody //将数据转换为json格式发送给前端
    //RequestParam 必须加此 注解 否则无法接受到
    public LayuiPage<Menu> limitMenu2(@RequestParam Map<String, String> parms) {
        return canteenService.menuList2(parms);
    }

    @RequestMapping("/Rflist")
    @ResponseBody //将数据转换为json格式发送给前端
    //RequestParam 必须加此 注解 否则无法接受到
    public LayuiPage<Restaurant_food> limitRf(@RequestParam Map<String, String> parms) {
        canteenService.rfTestList();
        return canteenService.RfList(parms);
    }

    @RequestMapping("/deleteMenu")
    @ResponseBody
    public R removeById(@RequestParam("id") Integer ids) {

        int i = canteenService.removeById(ids);
        if (i > 0) {
            return R.success("删除数据成功");
        } else {
            return R.error("删除数据失败");
        }
    }

    @RequestMapping("/deleteMenus")
    @ResponseBody
    public R deleteAll(@RequestParam("id") String idstr) {

        System.out.println(idstr);
        int length = idstr.split(",").length;

        int count = canteenService.deleteAll(idstr);

        if (count == length) {
            return R.success("所有数据删除成功");
        } else {
            return R.success("所有数据全部删除失败：已删除" + count);
        }

    }
    @RequestMapping("/update")
    @ResponseBody
    public R updateStudent(Menu menu) {
        System.out.println(menu);
        int i = canteenService.updateMenu(menu);

        if (i > 0) {
            return R.success("修改数据成功");
        } else {
            return R.error("修改数据失败");
        }

    }

    @RequestMapping("/add")
    @ResponseBody
    public R addMenu(Menu menu) {

        int i = canteenService.addMenu(menu);

        if (i > 0) {
            return R.success("添加数据成功");
        } else {
            return R.error("添加数据失败");
        }

    }
    @RequestMapping("/rfadd")
    @ResponseBody
    public R rfadd(Restaurant_food rf) {

        int i = canteenService.rfadd(rf);

        if (i > 0) {
            return R.success("添加成功");
        } else {
            return R.error("添加失败");
        }

    }

    @RequestMapping("/pay")
    @ResponseBody
    public R getPriceById(@RequestParam("userId")Integer userId,@RequestParam("paypassword")String paypassword,@RequestParam("foodId")Integer foodId,@RequestParam("menuId")Integer[] menuId,@RequestParam("out")Integer out) {

        for (int men:
             menuId) {
            System.out.println("*******************************************");
            System.out.println(men);
        }
        int i = 0;
        int allprice = canteenService.getallprice(menuId, out);
        User user = canteenService.ProvePayUser(userId, paypassword);
        if (user != null){
            i= canteenService.Pay(userId, menuId, foodId, out);
        }else {
            return R.error("支付密码错误！！");
        }
        if (user.getMoney()<allprice){
            return R.error("您的余额不足，请检查");
        }
        if (i > 0) {
            return R.success("购买成功了，请及时取餐哦");
        } else {
            canteenService.rfTestList(foodId);
            return R.error("出餐异常，可能是食材不足，正在联系管理员");
        }
    }


    @RequestMapping("/upload")
    @ResponseBody
    public R<String> upload(MultipartFile file) {

        if (file != null) {  //判断空 处理是为了避免 前端的预检查请求
            try {
                String filename = file.getOriginalFilename();
                InputStream inputStream = file.getInputStream();
                String pic = OSSUtil.uploadFile(inputStream, filename);
                // 将生成的图片的oss的url地址发送给前端
                System.out.println(R.success(pic));
                return R.success(pic);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return R.error("文件上传失败");
    }


    @RequestMapping("/templateDownload")   //excel模板文件的下载
    @ResponseBody
    public void templateDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //下载excel 的 响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //读取服务器上的模板文件 写到浏览器
        //得到模板文件的路径
        //request.getServletContext() 得到上下文环境  /代表资源根目录
        String realPath = request.getServletContext().getRealPath("/template/菜单信息模板.xlsx");

        //根据文件路径 创建File 对象
        File file = new File(realPath);

        // 把File  对象转为 字节数组
        byte[] bytes = FileUtils.readFileToByteArray(file);
        // 下载的文件名 是中文  要进行转码  要不然会出现乱码
        String filename = URLEncoder.encode("菜单信息模板", "utf-8");

        // 告诉浏览器  下载文件
        response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xlsx");

        //得到指向浏览器的输出流  向浏览器写输出
        ServletOutputStream outputStream = response.getOutputStream();
        // 把字节数组 输出到浏览器
        outputStream.write(bytes);

        outputStream.close();
    }


    // 读取excel 文件数据 存到数据库中
    @RequestMapping("/import")
    @ResponseBody
    public R importExcel(MultipartFile file) throws IOException {
        // 避免预检请求报错
        if (file != null) {
            /**
             * 参数1  文件流
             * 参数2  读取到的数据封装到哪个数据类型中
             * 参数3  监听器  每读取一行数据 就会调用监听器中的 invoke  方法
             * */
            ExcelReaderBuilder read = EasyExcel.read(file.getInputStream(), MenuBo.class, webCanteenListener);
            // 得到 sheet 对象
            ExcelReaderSheetBuilder sheet = read.sheet();
            // 读取sheet
            sheet.doRead();

        }
        return R.success("全部数据插入完成!");
    }

    //导出列表数据   把满足条件的数据 查询出来  写到excel 中  把excel 写到浏览器
    @RequestMapping("/export")
    public void export(Menu menu, HttpServletResponse response) throws IOException {
        //下载excel 的 响应数据格式
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 下载的文件名 是中文  要进行转码  要不然会出现乱码
        String filename = URLEncoder.encode("菜单导出", "utf-8");

        // 告诉浏览器  需要下载文件
        response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xlsx");

        //得到指向浏览器的输出流  向浏览器写输出
        ServletOutputStream outputStream = response.getOutputStream();

        ExcelWriterBuilder write = EasyExcel.write(outputStream, MenuBo.class);

        ExcelWriterSheetBuilder sheet = write.sheet();
        //准备满足条件的集合数据
        List<MenuBo> MenuBos = canteenService.MenuExcelData(menu);
        // 把这个集合数据 写到 输出流
        sheet.doWrite(MenuBos);
    }



}
